<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="filters.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <org-unit-select v-model="filters.orgUnitId" placeholder="请选择店铺" :org-unit-type="1" />
      <el-radio-group v-model="filters.type" style="margin: 0 3px;">
        <el-radio-button :label="1" @click.native.prevent="typeFilter(1)">折扣券</el-radio-button>
        <el-radio-button :label="2" @click.native.prevent="typeFilter(2)">金额券</el-radio-button>
      </el-radio-group>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canAddEntity" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleAdd">定义优惠券</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="name" label="名称" min-width="180" />
      <el-table-column prop="orgUnitName" label="所属店铺" min-width="260" />
      <el-table-column prop="type" label="类型" width="120" :formatter="formatType" />
      <el-table-column prop="amount" label="额度" width="120" :formatter="formatAmount" />
      <el-table-column prop="movieLevelName" label="适用剧本类别" width="120" />
      <el-table-column prop="maxAmount" label="最大抵扣金额(元)" width="160" :formatter="formatMaxAmount" />
      <el-table-column label="操作" width="280" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="优惠券信息" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="addForm.type" style="margin: 0 3px;" >
            <el-radio-button :label="1">折扣券</el-radio-button>
            <el-radio-button :label="2">金额券</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="适用剧本类别">
          <movie-level-select v-model="addForm.movieLevelId" :show-unselect-item="true" unselect-text="无限制"/>
        </el-form-item>
        <el-form-item :label="amountLabel" prop="amount">
          <el-input-number v-model="addForm.amount" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item v-if="addForm.type === 1" label="最大抵扣金额(元)" prop="maxAmount">
          <el-input-number v-model="addForm.maxAmount" :min="-1" controls-position="right" />
          <el-tooltip content="-1代表无限制"><i class="el-icon-question" style="font-size: 22px;"></i></el-tooltip>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { saveCoupon, modifyCoupon, deleteCoupon, listCoupon } from '@/api/coupon-def'
import OrgUnitSelect from '../components/org-unit-select'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import util from '@/utils/util.js'
import MovieLevelSelect from '@/views/components/movie-level-select'

export default {
  name: 'CouponDef',
  components: { MovieLevelSelect, Pagination, OrgUnitSelect },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        name: '',
        orgUnitId: null,
        type: null
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },

      // 新增界面是否显示
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }]
      },
      // 新增界面数据
      recordId: 0,
      addForm: {
        name: '',
        type: null,
        amount: null,
        movieLevelId: null,
        maxAmount: null
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth']),
    canAddEntity() {
      const roles = this.userInfo.roles || []
      if (roles.indexOf('Admin') !== -1) {
        return true
      }
      if (roles.indexOf('Manager') !== -1) {
        if (this.userInfo.orgUnitType === 1) {
          // 店铺
          return true
        }
      }
      return roles.indexOf('ShopManager') !== -1
    },
    amountLabel() {
      return this.addForm.type === 1 ? '额度(%)' : '额度(元)'
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    formatType(row) {
      if (row.type === 1) {
        return '折扣券'
      } else if (row.type === 2) {
        return '金额券'
      } else {
        return '未知类型'
      }
    },
    formatAmount(row) {
      if (row.type === 1) {
        // 折扣券
        return row.amount + '%'
      } else {
        return util.currency.format(row.amount) + '元'
      }
    },
    formatMaxAmount(row) {
      if (row.type === 1) { // 折扣券才有最大抵扣金额
        if (row.maxAmount === -1) {
          return '无限制'
        }
        return util.currency.format(row.maxAmount)
      } else {
        return ''
      }
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      listCoupon(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    typeFilter(type) {
      if (type === this.filters.type) {
        this.filters.type = null
      } else {
        this.filters.type = type
      }
      this.handleFilter()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.recordId = null
      this.addForm.name = ''
      this.addForm.type = null
      this.addForm.movieLevelId = null
      this.addForm.amount = 0
      this.addForm.maxAmount = 0
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.recordId = row.id
      this.addForm.name = row.name
      this.addForm.type = row.type
      this.addForm.movieLevelId = row.movieLevelId
      this.addForm.amount = row.type === 1 ? row.amount : row.amount / 100
      this.addForm.maxAmount = row.type === 1 ? (row.maxAmount === -1 ? -1 : row.maxAmount / 100) : row.maxAmount
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            if (this.recordId) {
              this.doEdit()
            } else {
              this.doAdd()
            }
          })
        }
      })
    },
    doAdd() {
      const param = { ...this.addForm }
      if (param.type === 1) {
        if (param.maxAmount !== -1) {
          param.maxAmount = parseInt((param.maxAmount * 100) + '')
        }
      } else {
        param.amount = parseInt((param.amount * 100) + '')
      }
      saveCoupon(param).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    doEdit() {
      const param = { ...this.addForm }
      if (param.type === 1) {
        if (param.maxAmount !== -1) {
          param.maxAmount = parseInt((param.maxAmount * 100) + '')
        }
      } else {
        param.amount = parseInt((param.amount * 100) + '')
      }

      modifyCoupon(this.recordId, param).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '保存失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    handleDelete(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteCoupon(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
